/**
 * 
 */
package org.alipay4j.component;

import org.alipay4j.Alipay;
import org.alipay4j.AlipayException;
import org.alipay4j.AlipaySupport;
import org.alipay4j.http.Response;
import org.alipay4j.util.ObjectHelper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 支付宝组件基础类
 * @author 贺亮
 *
 */
public class AbstractComponent extends AlipaySupport {
	
	protected Alipay alipay;

    public AbstractComponent(Alipay alipay) {
        if (alipay == null) {
            throw new IllegalArgumentException("alipay can not be null");
        }
        this.alipay = alipay;
    }
    
    /**
     * 返回不同业务的参数对象
     * @param key
     * @return
     */
    public JSONObject getObjRes(Response response,String key) throws AlipayException  {
    	JSONObject resJson =  response.asJSONObject();
    	JSONObject errorRes = resJson.getJSONObject("error_response");
    	JSONObject bodyRes = null;
    	if(ObjectHelper.isEmpty(errorRes)) {
    		bodyRes = resJson.getJSONObject(key);
    	} else {
    		String sub_code = errorRes.getString("sub_code");
        	String sub_msg = errorRes.getString("sub_msg");
            //返回异常信息
            throw new AlipayException(getCause(sub_code,sub_msg));
    	}
    	return bodyRes;
    }
    
    /**
     * 返回不同业务的集合对象
     * @param key
     * @return
     */
    public JSONArray getListRes(Response response,String key) throws AlipayException  {
    	JSONObject resJson =  response.asJSONObject();
    	JSONObject errorRes = resJson.getJSONObject("error_response");
    	JSONArray listRes = null;
    	if(ObjectHelper.isEmpty(errorRes)) {
    		listRes = resJson.getJSONArray(key);
    	} else {
    		String sub_code = errorRes.getString("sub_code");
        	String sub_msg = errorRes.getString("sub_msg");
            //返回异常信息
            throw new AlipayException(getCause(sub_code,sub_msg));
    	}
    	return listRes;
    }
}
